package com.smartfast4j.sys.web;


import com.smartfast4j.common.result.JsonResult;
import com.smartfast4j.sys.entity.User;
import com.smartfast4j.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author 孤傲苍狼
 * @since 2017-08-28
 */
@Controller
public class UserController extends BaseController{

    @Autowired
    private IUserService userService;

    @RequestMapping("/preSave")
    public ModelAndView preSave(ModelAndView modelAndView, @RequestParam(value = "id", required = false) Long id) {
        modelAndView.setViewName("save");
        //modelAndView.setViewName("save.jsp");
        if (id != null) {
            modelAndView.addObject("user", userService.selectById(id));
        }
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("save")
    public Object save(User user) {
        if (user.getId() == null) {
            return userService.insert(user) ? renderSuccess("添加成功") : renderError("添加失败");
        } else {
            return userService.updateById(user) ? renderSuccess("修改成功") : renderError("修改失败");
        }
    }

    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(@RequestParam(value = "id", required = false) Long id) {
        return userService.deleteById(id) ? renderSuccess("删除成功") : renderError("删除失败");
    }

    @ResponseBody
    @RequestMapping("/getUserByName")
    public JsonResult getUserByName(@RequestParam(value = "name", required = true) String name){
        User user = userService.getUserByName(name);
        if(user != null){
            return renderSuccess(user);
        }else {
            return renderError("查询失败");
        }
    }

    @ResponseBody
    @RequestMapping("/getUserById")
    public JsonResult getUserById(@RequestParam(value = "id", required = true) Long id){
        User user = userService.selectByPrimaryKey(id);
        if(user != null){
            return renderSuccess(user);
        }else {
            return renderError("查询失败");
        }
    }

    @ResponseBody
    @RequestMapping("/deleteUserById")
    public Object deleteUserById(@RequestParam(value = "id", required = true) Long id) {
        return userService.deleteByPrimaryKey(id)>0 ? renderSuccess("删除成功") : renderError("删除失败");
    }
}
